<?php

namespace app\agent\controller;

use app\common\Common;
use app\common\BaseHelper;

use app\agent\model\Tenant as TenantMdl;

use think\Db;
use think\Exception;
use think\Request;

/**
 * 商户
 */
class Tenant extends Base
{

    protected $ifAdd = true; // 是否可以开通商户

    public function _initialize()
    {

        $this->exceptAction = ['ajaxTenantList'];
        parent::_initialize();

        if($this->agentInfo){
            // 当前代理商信息
            $this->assign('agentInfo', $this->agentInfo);
            // 代理商余额需大于等于开通商户费用
            if($this->agentInfo->rechargeAmount < $this->agentInfo->buyingPrice){
                $this->ifAdd = false;
            }
        }

        // 是否有余额开通商户
        $this->assign('ifAdd', $this->ifAdd);
    }

    public function index(){
        // 经营类目
        $industryCate = $this->getIndustryCategory();
        $this->assign('industryCate', $industryCate);

        return $this->view->fetch();
    }

    public function ajaxTenantList(){
        $request = $this->request;
        $param = $request->param();
        $model = model($this->model);

        // 每页起始条数
        $start = $param['start'];
        // 每页显示条数
        $length = $param['length'];
        // 排序条件
        $columns = $param['order'][0]['column'];
        $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];

        $where = [
            //'a.isActive' => 1
        ];
        if($this->agentInfo){
            // 当前代理商可见的商户ID数组
            $ids = $this->getAccessTenantIds();
            $where['createOper'] = ['in', $ids];
        }
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);
            if($filter['code']){
                $where['code'] = ['like', '%'.$filter['code'].'%'];
            }
            if($filter['name']){
                $where['name'] = ['like', '%'.$filter['name'].'%'];
            }
            if(isset($filter['category']) && !empty($filter['category'])){
                $where['category'] = ['in', $filter['category']];
            }
            if(isset($filter['district']) && !empty($filter['district'])){
                $where['city'] = ['in', $filter['district']];
            }
            if(isset($filter['loginName']) && $filter['loginName']){
                //
            }
        }

        /*$join = [
            ['__OPERATOR__ u', 'a.id = u.tenantId'],
        ];
        $field = 'a.*, u.loginName';*/
        $list = $model->alias('a')->where($where)->limit($start, $length)->order($order)->select();
        $count = $model->alias('a')->where($where)->count();
        foreach ($list as &$item) {
            $user = db('operator')->where(['tenantId' => $item->id, 'storeId' => 0, 'roleType' => 0])->field('loginName')->find();
            $item->loginName = $user['loginName'];
            $agent = db('agent')->where(['id' => $item->createOper])->field('name')->find();
            $item->agentName = $agent['name'];
        }

        $result = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];

        return json($result);
    }

    public function add(){
        // 经营类目
        $industryCate = $this->getIndustryCategory();
        // 商户编号
        $tenant = db('tenant')->order('code', 'DESC')->field('code')->find();
        $code = $tenant ? (int)($tenant['code'] + 1) : 100010;

        $this->assign('industryCate', $industryCate);
        $this->assign('code', $code);

        return $this->view->fetch();
    }

    public function addPost(){
        $request = $this->request;
        if($this->request->isAjax()) {
            $model = model($this->model);
            $data = $this->request->param();
            // Insert data
            $data['id'] = BaseHelper::getUUID();
            $data['createDate'] = date('Y-m-d H:i:s');
            // 商户余额
            //$data['balance'] = $this->agentInfo->buyingPrice;

            try {
                Db::startTrans();
                // 商户余额
                $agent = db('agent')
                    ->alias('a')
                    ->where(['a.id' => $data['createOper']])
                    ->join('__AGENTPOLICY__ l', 'a.levelId = l.id')
                    ->field('a.rechargeAmount, l.buyingPrice')
                    ->find();

                $data['balance'] = $agent['buyingPrice'];
                // 选择的代理商 是否有月开户
                if($agent['rechargeAmount'] < $data['balance']){
                    return json(['status' => 0, 'msg' => '该代理商余额不够开通商户，请先续费！']);
                }
                // 账号名检查
                if($this->checkName($data['loginName'])){
                    return json(['status' => 0, 'msg' => '该账号名已存在！']);
                }
                $result = $model->save($data);

                if($result !== false) {
                    // 开通商户日志
                    $this->handleAgentOpenLog($data);
                    // 开通商户 代理商减去费用
                    $this->handleAgent($data);
                    // 商户管理员
                    $userData = [
                        'id' => '',
                        'name' => $data['loginName'],
                        'createDate' => date('Y-m-d H:i:s'),
                        'loginName' => $data['loginName'],
                        'password' => md5($data['password']),
                        'phone' => $data['phone'],
                        'tenantCode' => $data['code'],
                        'tenantId' => $data['id'],
                        'storeId' => 0,
                        'roleType' => 0
                    ];
                    $res = $this->handleOperator($userData);

                    if($res){
                        Db::commit();
                        // 写入日志
                        $logInfo = $this->admin->loginName . '添加了一条' . $this->model . '数据。';
                        common::agentLog($request, $logInfo);

                        return json(['status' => 1, 'msg' => '开通成功！']);
                    }else{
                        Db::rollback();
                        return json(['status' => 0, 'msg' => '开通失败！']);
                    }
                } else {
                    return json(['status' => 0, 'msg' => '开通失败！']);
                }
            } catch (Exception $e) {
                return json(['status' => 0, 'msg' => $e->getMessage()]);
            }
        } else {
            return json(['status' => 0, 'msg' => '请求方式不正确！']);
        }
    }

    public function edit(){
        $model = model($this->model);
        $id = $this->request->param('id');
        $where = [
            'a.id' => $id,
            'u.storeId' => 0,
            'u.roleType' => 0
        ];
        $join = [
            ['__OPERATOR__ u', 'a.id = u.tenantId'],
            ['__AGENT__ ag', 'a.createOper = ag.id'],
        ];
        $field = 'a.*, u.id as userId, u.loginName, u.password, ag.name as agentName';
        $info = $model->alias('a')->where($where)->join($join)->field($field)->find();

        if(!$info){
            return $this->error('error !', 'agent/tenant/index');
        }
        // 经营类目
        $industryCate = $this->getIndustryCategory();
        $this->assign('industryCate', $industryCate);
        $this->assign('info', $info);

        return $this->view->fetch();
    }

    public function editPost(){
        $request = $this->request;
        if($this->request->isAjax()) {
            $model = model($this->model);
            $data = $this->request->param();
            // Update data
            $data['updateDate'] = date('Y-m-d H:i:s');

            try {
                Db::startTrans();
                if($this->checkName($data['loginName'], $data['userId'])){
                    return json(['status' => 0, 'msg' => '该账号名已存在！']);
                }
                $result = $model->allowField(true)->save($data, ['id' => $data['id']]);

                if($result !== false) {
                    // 商户管理员
                    $userData = [
                        'id' => $data['userId'],
                        'name' => $data['loginName'],
                        'updateDate' => date('Y-m-d H:i:s'),
                        'loginName' => $data['loginName'],
                        'phone' => $data['phone'],
                        'tenantCode' => $data['code'],
                        'tenantId' => $data['id'],
                        'storeId' => 0,
                        'roleType' => 0
                    ];
                    if(trim($data['password']) && $data['password'] != $data['ori_password']){
                        $userData['password'] = md5($data['password']);
                    }
                    $res = $this->handleOperator($userData);

                    if($res){
                        Db::commit();
                        // 写入日志
                        $logInfo = $this->admin->loginName . '更新了一条' . $this->model . '数据。';
                        common::agentLog($request, $logInfo);

                        return json(['status' => 1, 'msg' => '保存成功！']);
                    }else{
                        Db::rollback();
                        return json(['status' => 0, 'msg' => '保存失败！']);
                    }
                } else {
                    return json(['status' => 0, 'msg' => '保存失败！']);
                }
            } catch (Exception $e) {
                return json(['status' => 0, 'msg' => $e->getMessage()]);
            }
        } else {
            return json(['status' => 0, 'msg' => '请求方式不正确！']);
        }
    }

    /**
     * 详情
     */
    public function view(){
        $id = $this->request->param('id');
        if(!$id){
            return json(['status' => 0, 'msg' => '参数错误！']);
        }

        $model = model($this->model);
        $info = $model->where(['id' => $id])->find();
        if(!$info){
            return json(['status' => 0, 'msg' => '该商户不存在！']);
        }

        $user = db('operator')->where(['tenantId' => $info->id, 'storeId' => 0, 'roleType' => 0])->field('loginName')->find();
        $info->loginName = $user['loginName'];
        $agent = db('agent')->where(['id' => $info->createOper])->field('name')->find();
        $info->agentName = $agent['name'];

        //return json(['status' => 1, 'data' => $info]);
        $this->assign('info', $info);

        return json(['status' => 1, 'data' => $this->fetch('')]);
    }

    /**
     * 获取商户 经营类目
     */
    public function getIndustryCategory(){
        // 经营类目
        $industryModel = db('industrycategory');
        $industryCate = $industryModel->where(['parentId' => 0])->select();
        /*foreach ($industryCate as &$item) {
            $item['child'] = $industryModel->where(['parentId' => $item['id']])->select();
        }*/

        return $industryCate;
    }

    /**
     * 获取当前代理商可见的商户 ID 数组
     */
    public function getAccessTenantIds(){
        $ids = [$this->agentId];

        return $ids;
    }

    /**
     * 代理商 开通商户日志
     */
    public function handleAgentOpenLog($data){
        if(!$data){
            return false;
        }

        try {
            $model = db('agentopenlog');
            $addData = [
                'id' => BaseHelper::getUUID(),
                'agentId' => $data['createOper'],
                'tenantId' => $data['id'],
                'openCost' => $data['balance'],
                'createDate' => time()
            ];
            $result = $model->insert($addData);

            if($result !== false){
                return true;
            }else{
                return false;
            }
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * 代理商 减开户费用 & 开通商户数 +1
     */
    public function handleAgent($data){
        if(!$data){
            return false;
        }

        try {
            $model = model('Agent');
            Db::startTrans();
            // 开户费用
            $openAccountCost = $data['balance'];
            $result = $model->where(['id' => $data['createOper']])->setDec('rechargeAmount', $openAccountCost);

            if($result !== false){
                // 开通商户数 +1
                $res = $model->where(['id' => $data['createOper']])->setInc('hasOpenNum', 1);
                if($res){
                    Db::commit();
                    return true;
                }else{
                    Db::rollback();
                    return false;
                }
            }else{
                return false;
            }
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * 商户后台管理员
     */
    public function handleOperator($data){
        if(!$data){
            return false;
        }

        try {
            $model = model('Operator');
            if($data['id']){
                $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
            }else{
                $data['id'] = BaseHelper::getUUID();
                $result = $model->save($data);
            }

            if($result !== false){
                return true;
            }else{
                return false;
            }
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * 检查用户名是否已存在
     */
    public function checkName($loginName, $id = ''){
        //$loginName = $this->request->param('loginName');
        $operatorDB = db('operator');
        if($id){
            $info = $operatorDB->where(['id' => $id])->field('loginName')->find();
            if($info['loginName'] == $loginName){
                return false;
            }
        }
        $admin = $operatorDB->where(['loginName' => $loginName, 'roleType' => 0])->field('loginName')->find();

        if($admin){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 续费
     */
    public function renewalFee(){
        $id = $this->request->param('id');
        if(!$id){
            return json(['status' => 0, 'msg' => '参数错误！']);
        }

        $model = model($this->model);
        $info = $model->where(['id' => $id])->find();
        if(!$info){
            return json(['status' => 0, 'msg' => '该商户不存在！']);
        }

        $agent = db('agent')->where(['id' => $info->createOper])->field('name')->find();
        $info->agentName = $agent['name'];

        $this->assign('info', $info);

        return json(['status' => 1, 'data' => $this->fetch('')]);
    }

    /**
     * 续费提交
     */
    public function renewalFeePost(){
        $request = $this->request;
        if($this->request->isAjax()){
            $id = $this->request->param('id');
            if(!$id){
                return json(['status' => 0, 'msg' => '参数错误！']);
            }

            $model = model($this->model);
            $balance = $this->request->param('renewal_money');
            $result = $model->where(['id' => $id])->setInc('balance', $balance * 100);
            if($result !== false){
                // 写入日志
                $logInfo = $this->admin->loginName . '续费了1条' . $this->model . '数据。';
                common::agentLog($request, $logInfo);

                return json(['status' => 1, 'msg' => '续费成功！']);
            }else{
                return json(['status' => 0, 'msg' => '续费失败！']);
            }
        }
    }

    /**
     * 启用
     */
    public function enable(){
        $request = $this->request;
        if($this->request->isAjax()){
            $model = model($this->model);
            $id = $this->request->param('id');
            if(!$id){
                return json(['status' => 0, 'msg' => '参数错误！']);
            }

            $data = [
                'id' => $id,
                'isActive' => 1
            ];
            $result = $model->save($data, ['id' => $data['id']]);
            if($result !== false){
                // 写入日志
                $logInfo = $this->admin->loginName . '启用了1条' . $this->model . '数据。';
                common::agentLog($request, $logInfo);

                return json(['status' => 1, 'msg' => '启用成功！']);
            }else{
                return json(['status' => 0, 'msg' => '启用失败！']);
            }
        }
    }

    /**
     * 禁用
     */
    public function disable(){
        $request = $this->request;
        if($this->request->isAjax()){
            $model = model($this->model);
            $id = $this->request->param('id');
            if(!$id){
                return json(['status' => 0, 'msg' => '参数错误！']);
            }

            $data = [
                'id' => $id,
                'isActive' => 0
            ];
            $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
            if($result !== false){
                // 写入日志
                $logInfo = $this->admin->loginName . '禁用了1条' . $this->model . '数据。';
                common::agentLog($request, $logInfo);

                return json(['status' => 1, 'msg' => '禁用成功！']);
            }else{
                return json(['status' => 0, 'msg' => '禁用失败！']);
            }
        }
    }
}